<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="编号" prop="configCode">
        <el-input
          v-model="queryParams.configCode"
          placeholder="请输入步配置编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="configName">
        <el-input
          v-model="queryParams.configName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['co:config:addXsOrderConfig']"
        >新增</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column label="配置编号" align="center" prop="configCode" >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['co:config:queryXsOrderConfig']"
          >{{scope.row.configCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="配置名称" align="center" prop="configName" />
      <el-table-column label="是否启用" align="center" prop="status" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
                       :active-value="1"
                       :inactive-value="0"
                       active-color="#13ce66"
                       active-text="启用"
                       @change="handleStatus(scope.row,$event)">
            </el-switch>
          </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['co:config:editXsOrderConfig']"
            v-if="scope.row.status==0"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['co:config:removeXsOrderConfig']"
            v-if="scope.row.status==0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改多级审批设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入配置名称" :readonly="optType=='view'"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核层数" prop="totalStep">
              <el-input-number :min="1" :max="10" :disabled="optType=='view'"
                               v-model="form.totalStep" placeholder="请输入审核层数" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="createSteps()"
              v-if="optType!='view'"
            >生成配置明细</el-button>
          </el-col>

        </el-row>

        <el-table id="stepTable" v-loading="loading" :data="form.stepList" style="overflow: visible" >
          <el-table-column label="步骤" align="center" prop="stepType" width="150">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.stepType"  placeholder="" :disabled="true">
                          <el-option
                            v-for="s in stepTypeOptions"
                            :key="s.id"
                            :label="s.name"
                            :value="s.id">
                          </el-option>
                        </el-select>
                    </template>
          </el-table-column>
          <el-table-column label="步骤名称" align="center" prop="stepName"  width="150">
            <template slot-scope="scope">
                <el-input v-model="scope.row.stepName" placeholder="" :disabled="scope.row.stepType==0||optType=='view'" />
              <span v-if="!scope.row.stepName && isSubmitted" style="color: red;">不能为空</span>
            </template>
          </el-table-column>
          <el-table-column label="审批人" align="center" prop="deptName" class="step-user-col">
            <template slot-scope="scope">
              <div style="display:flex;">
              <treeselect  v-model="scope.row.deptId":disabled="optType=='view'" :options="deptOptions" v-if="scope.row.stepType>0" :show-count="true" placeholder="请选择归属部门" style="width: 230px" @select="getUserList(scope.row,$event)"/>
              <el-select filterable v-model="scope.row.userId":disabled="optType=='view'"   placeholder="" v-if="scope.row.stepType>0" >
                <el-option
                  v-for="s in scope.row.userOptions"
                  :key="s.userId"
                  :label="s.nickName"
                  :value="s.userId">
                </el-option>
              </el-select>

              </div>
              <span v-if="!scope.row.userId && isSubmitted&&scope.row.stepType>0" style="color: red;">审批人不能为空</span>
            </template>
          </el-table-column>

          <el-table-column label="通过后显示状态" align="center" prop="yesStatusWords"  width="150">
            <template slot-scope="scope">
                <el-input v-model="scope.row.yesStatusWords" placeholder="" :readonly="optType==='view'"/>
              <span v-if="!scope.row.yesStatusWords && isSubmitted" style="color: red;">不能为空</span>
            </template>
          </el-table-column>
          <el-table-column label="驳回后显示状态" align="center" prop="noStatusWords"  width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.noStatusWords" placeholder="" :readonly="optType=='view'" v-if="scope.row.stepType>0"/>
              <span v-if="!scope.row.noStatusWords && isSubmitted&&scope.row.stepType>0" style="color: red;">不能为空</span>
            </template>
          </el-table-column>

        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType!='view'" >确 定</el-button>
        <el-button @click="cancel"  v-if="optType!='view'">取 消</el-button>
        <el-button @click="cancel"  v-if="optType=='view'">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  xsOrderConfiglist,
  addXsOrderConfig,
  xsOrderConfigUpdateStatus, queryXsOrderConfig, editXsOrderConfig, delXsOrderConfig
} from "@/api/mes/co/config";
import Template from "@/views/print/printtemplate/list.vue";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listUser} from "@/api/system/user";
import request from "@/utils/request";

export default {
  name: "Config",
  components: {Treeselect, Template},
  dicts:['sys_yes_no'],
  data() {
    return {
      optType:'view',
      stepTypeOptions:[{id:0,name:'提交审批'},{id:1,name:'一级审批'},{id:2,name:'二级审批'},
        {id:3,name:'三级审批'},{id:4,name:'四级审批'},{id:5,name:'五级审批'},{id:6,name:'六级审批'},
        {id:7,name:'七级审批'},{id:8,name:'八级审批'},{id:9,name:'九级审批'},{id:10,name:'十级审批'}],

      // 遮罩层
      loading: true,
      // 部门树选项
      deptOptions: undefined,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isSubmitted:false,
      // 总条数
      total: 0,
      // 多级审批设置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,        stepType: null,        stepName: null,        deptName: null,        nickName: null,      },
      // 表单参数
      form: {  stepList:[{totalStep:0,stepType:0,stepName:'提交审批',deptId:null,deptName:null,userId:null,nickName:null,yesStatusWords:'待审批',
          noStatusWords:'',yesStatus: 0,noStatus: 0}],},
      // 表单校验
      rules: {
        totalStep: [
          { required: true, message: "总步数不能为空", trigger: "blur" }
        ],        status: [
          { required: true, message: "是否启用不能为空", trigger: "blur" }
        ],          }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    handleStatus(row,status){
      let words=status==1?'启用':'停用';
      this.$modal.confirm(`是否确认${words}？` ).then(function() {
       return xsOrderConfigUpdateStatus({configCode: row.configCode, status: status});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
          this.getList();
      });
    },
    getUserList(row,v){
      row.userOptions=[];
      row.userId=null;
      listUser({deptId:v.id}).then(response => {
          row.userOptions = response.rows;
        }
      );
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        // debugger;
        this.deptOptions = response.data;
      });
    },
    createSteps(){
      this.form.stepList=[{totalStep:this.form.totalStep,stepType:0,stepName:'提交审批',deptId:null,deptName:null,userId:null,nickName:null,yesStatusWords:'待审批',noStatusWords:'',yesStatus: 0,noStatus: 0}];
      for (let i = 1; i <= this.form.totalStep; i++) {
        this.form.stepList.push({userOptions:[],totalStep:this.form.totalStep,stepType:i,stepName:i+'级审批',deptId:null,deptName:null,userId:null,nickName:null,yesStatusWords:'待审批',noStatusWords:'驳回',yesStatus: i,noStatus: -i})
      }
    },
    /** 查询多级审批设置列表 */
    getList() {
      this.loading = true;
      xsOrderConfiglist(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.isSubmitted=false
      this.form = {
        id: null,        configCode: null,        totalStep: null,
        stepList:[{totalStep:this.form.totalStep,stepType:0,stepName:'提交审批',deptId:null,deptName:null,userId:null,nickName:null,yesStatusWords:'待审批',noStatusWords:'',yesStatus: 0,noStatus: 0}]

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.optType='add'
      this.title = "添加多级审批设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getOne(row,"修改多级审批设置","edit");
    },
    async  fetchUserOptions(stepList) {
      for (let i = 1; i < stepList.length; i++) {
        const re = await listUser({ deptId: stepList[i].deptId });
        this.form.stepList[i].userOptions=re.rows;
      }
    },
    getOne(row,title,optType){
      this.optType=optType
      const configCode = row.configCode
      this.reset()
      queryXsOrderConfig(configCode).then(response => {
        this.form=response.data;
        this.fetchUserOptions(response.data.stepList).then(() => {
          this.open = true;
          this.title = title;
        })
      });
    },
    handleView(row){
      this.getOne(row,"查看审批设置","view");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.stepList.length == this.form.totalStep+1 && this.form.totalStep >=1) {
            this.isSubmitted = true;
            let l=0;
            this.form.stepList.forEach((row, index) => {
              if (index>0&&(!row.stepName || !row.userId || !row.yesStatusWords || !row.noStatusWords)) {
                l=index;
                valid = false;
                return;
              }
            });
          if(valid){
            if (this.form.configCode != null) {
              editXsOrderConfig(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addXsOrderConfig(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
          }else{
            this.$modal.msgError("请根据审核层数生成配置明细！");
          }
        }else{
          this.$modal.msgError("请完善表单信息");
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configCodes = row.configCode || this.ids;
      this.$modal.confirm('是否确认删除多级审批设置编号为"' + configCodes + '"的数据项？').then(function() {
        return delXsOrderConfig(configCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('co/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" >
#stepTable {
  .el-table__body-wrapper {
    overflow: visible;
    .el-table__body {
      .el-table__row {
        .el-table__cell {
          .cell {
            overflow: visible;
          }
        }
      }
    }
  }
}
</style>
